//
//  HMNetworkTools.swift
//  Swift访问网络
//
//  Created by HM on 16/3/3.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import AFNetworking

/// 请求方式
///
/// - GET:  get
/// - POST: post
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class HMNetworkTools: AFHTTPSessionManager {
    
    /// 定义返回值的类型
    typealias HMRequestCallback = (responseObject: [String: AnyObject]?, error: NSError?)->()
    
    // 单例
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 提供请求数据的方法
    
    /// 请求数据的方法
    ///
    /// - parameter method:     请求方式
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter callback:   请求完成之后的闭包回调
    func requst(method: HMRequestMethod = .GET, urlString: String, parameters: AnyObject?, callback: HMRequestCallback) {
        
        
        // 拦截参数,往里面添加基础参数
        
        // 请求成功要执行的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) in
            
            // 判断返回数据是否是一个字典
            guard let responseDict = responseObject as? [String: AnyObject] else {
                // 如果发现不是字典
                callback(responseObject: nil, error: NSError(domain: "com.itheima.hahaha", code: 10001, userInfo: ["message": "返回数据不是字典"]))
                return
            }
            // 回调数据
            callback(responseObject: responseDict, error: nil)
        }
        
        // 请求失败要执行的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) in
            callback(responseObject: nil, error: error)
        }
        
        // 根据请求类型去调用不同的方法
        if method == .GET {
            self.GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            self.POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}

// MARK: - 发送微博相关请求的方法
extension HMNetworkTools {
    
    /// 发表图片微博
    ///
    /// - parameter status: <#status description#>
    func upload(status: String, image: UIImage, callback: HMRequestCallback){
        
        guard let accessToken = HMUserAccountViewModel.sharedAccountViewModel.accessToken else {
            callback(responseObject: nil, error: NSError(domain: "com.itheima", code: 1002, userInfo: ["errormsg": "accesstoken为nil"]))
            return
        }
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求方式
        let parameters = [
            "access_token" :accessToken,
            "status": status
        ]
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
            let data = UIImagePNGRepresentation(image)!
            // 拼接图片数据需要的闭包
            /**
            - 参数1:name -> 接口里面对应该文件的字段
            - 参数2:fileName ->
            - 参数3:mimeType --> 告诉后台我要传给你的文件是什么类型的
                - 大类型/小类型
                - image/png text/html text/json
                - 如果不知道是什么类型的话: application/octet-stream
            */
            formdata.appendPartWithFileData(data, name: "pic", fileName: "aabb", mimeType: "application/octet-stream")
        }, progress: nil, success: { (_, responseObject) -> Void in
            
            guard let dict = responseObject as? [String: AnyObject] else{
                // 如果发现不是字典
                callback(responseObject: nil, error: NSError(domain: "com.itheima.hahaha", code: 10001, userInfo: ["message": "返回数据不是字典"]))
                return
            }
            
            // 请求成功回调的闭包
            callback(responseObject: dict, error: nil)
        }) { (_, error) -> Void in
            // 请求失败回调的闭包
            callback(responseObject: nil, error: error)
        }
        
    }
    
    
    /// 发送文字微博的
    ///
    /// - parameter status:   微博内容
    /// - parameter callback: 发送完毕的回调
    func update(status: String, callback: HMRequestCallback){
        
        guard let accessToken = HMUserAccountViewModel.sharedAccountViewModel.accessToken else {
            callback(responseObject: nil, error: NSError(domain: "com.itheima", code: 1002, userInfo: ["errormsg": "accesstoken为nil"]))
            return
        }
        
        // 1. 定义url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 2. 定义参数
        let parameters = [
            "access_token": accessToken,
            "status": status
        ]
        requst(.POST, urlString: urlString, parameters: parameters, callback: callback)
    }

}
